<template>
  <n-flex class="ai-icon" align="center" @click="showAI=true">
    <n-icon :component="GlassesIcon" size="24" color="#ffffff"/>
  </n-flex>
  <!--  ai弹框-->
  <n-drawer v-model:show="showAI" width="27rem" placement="right">
    <n-drawer-content title="斯通纳" closable>
      <template #header>
        Linter AI智能答疑
      </template>
      <template #default>
        <n-empty v-if="!msg_arr.length" description="你还没有询问历史哦，试试问出你的疑问吧">
          <template #icon>
            <n-icon :component="ChatboxEllipsesIcon"></n-icon>
          </template>
        </n-empty>
        <n-virtual-list
            style="max-height: 100%"
            :item-size="42"
            :items="msg_arr"
            item-resizable
        >
          <!--    TODO：将v-if中的判断依据改为身份      -->
          <template #default="{ item, index }">
            <div v-if="item.rule==='ai'" :key="item.key" class="item item-ai">
              <img class="avatar" :src="item.avatar" alt="...">
              <span class="ai-window-content-bubble">{{ item.message }}</span>
            </div>
            <div v-else :key="item.key" class="item item-user">
              <span class="user-window-content-bubble">{{ item.message }}</span>
              <img class="avatar" :src="item.avatar" alt="">
            </div>
          </template>
        </n-virtual-list>
      </template>
      <template #footer>
        <n-space vertical :style="{width:'100%'}">
          <n-space>
            <n-text depth="3">猜你想问：</n-text>
            <n-carousel
                style="width: 12rem"
                autoplay
                draggable
                effect="slide"
                lides-per-view="auto"
                :show-dots="false"
                centered-slides
                :space-between="5"
            >
              <n-tag size="small" type="info" round>
                vue3介绍
              </n-tag>
              <n-tag size="small" type="primary" round>java循环语句</n-tag>
              <n-tag size="small" type="primary" round>python爬虫xpath规则</n-tag>
              <n-tag size="small" type="primary" round>
                  python爬虫requests库
              </n-tag>
              <n-tag size="small" type="primary" round>python爬虫selenium库</n-tag>
              <n-tag size="small" type="primary" round>python爬虫bs4库</n-tag>
            </n-carousel>
          </n-space>

          <n-space>
            <n-select size="tiny"
                      v-model:value="ai_type"
                      :options="ais"
                      keyboard
                      @update:value="hanleUpdateValue"
                      style="width: 7rem;"
            />
            <n-button text type="info" @click="summarizeClick">一键总结文章</n-button>

          </n-space>
          <n-input round
                   clearable
                   v-model:value="textareaValue"
                   maxlength="1000"
                   placeholder="请输入你的问题"
                   type="textarea"
                   @keyup.enter="sendingText"/>
          <n-space justify="space-between">
            <n-space>
              <n-icon size="18" class="hover-pointer icon-hover"><ImagesIcon class=""/></n-icon>
              <n-icon size="18" class="hover-pointer icon-hover"><LinkIcon/></n-icon>
              <n-icon size="18" class="hover-pointer icon-hover"><LocationIcon/></n-icon>
            </n-space>
            <n-space>
              <n-button type="info" size="small" @click="sendingText">
                发送
                <template #icon>
                  <n-icon :component="enterIcon"
                          size="16"
                          color="#657787"
                           />
                </template>
              </n-button>
            </n-space>
          </n-space>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script>
import {
  FlashOutline as searchIcon,
  PaperPlane as enterIcon,
  ChatboxEllipsesOutline as ChatboxEllipsesIcon,
  Glasses as GlassesIcon,
  ImagesOutline as ImagesIcon,
  LinkOutline as LinkIcon,
  LocationOutline as  LocationIcon
} from "@vicons/ionicons5"
import {ref,watch} from "vue";
// TODO: 未完善 需要继续修改
export default {
  name: "ai-util",
  components:{
    ImagesIcon,LinkIcon,LocationIcon
  },
  props:{
    section:{
      default:''
    }
  },
  setup( props,{emit}){
    //AI问答

    //接收用户输入的信息
    let textareaValue = ref(null)
    //流式数据存储
    let read_end = ref("");
    //流式数据渲染
    let reading = ref("")
    const avatar_ai = 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'
    //消息存储数组，里面保存对象{key:'',avatar:'',rule:'',message:''}
    let msg_arr = ref([
      {key:'1',avatar: avatar_ai,rule:'ai',message:'你好，请告诉我你的疑问把，我将尽力为你解答'},
    ])
    //消息框key设置
    let msg_count = 1
    // 创建 WebSocket 连接
    let ws;
    let ai_type = ref('ws://127.0.0.1:8888/ws')
    const ais=ref([
        {
          label:'linterAI',
          value:'ws://127.0.0.1:8888/ws',
          key:'ws'
        },
        {
          label:'javaAI',
          value: 'ws://127.0.0.1:8888/javaAi',
          key:'javaAi'
        },
      {
        label:'最新时事',
        value: 'ws://127.0.0.1:8888/newAi',
        key:'newAi'
      },
      {
        label:'星火大模型',
        value: 'ws://127.0.0.1:8888/sparkAi',
        key:'sparkAi'
      }
    ])
    function hanleUpdateValue() {
      // 监听连接关闭事件
      ws.onclose = () => {
        console.log('WebSocket disconnected');
        alert(666)
      };
      Aicontect(ai_type.value)
    }
    function summarizeClick() {
      sendMessage(props.section)
      msg_arr.value.push({
        key: msg_count++,
        avatar: avatar_ai,
        rule:'ai',
        message: " "
      })
    }
    function Aicontect(url='ws://127.0.0.1:8888/ws'){
      ws = new WebSocket(url);
      // 监听连接打开事件
      ws.onopen = () => {
        console.log('连接已经开始');
      };
      // 监听消息事件
      ws.onmessage = (event) => {
        reading.value = event.data
        read_end.value += reading.value
        msg_arr.value[msg_arr.value.length-1].message+=reading.value
        //如果停止输出就将最终结果显示到read_end
        if (!reading.value){
          read_end.value = ''
        }
      };
      // 监听连接关闭事件
      ws.onclose = () => {
        console.log('WebSocket disconnected');
      };

      // 监听连接错误事件
      ws.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
    }
   Aicontect();

    const sendMessage = (message) => {
      // 使用原生 WebSocket 发送消息
      ws.send(JSON.stringify({
        sender: 'User',
        content: message,
      }));
    };
    function sendingText(susu) {
      if(textareaValue.value===null || textareaValue.value === "" || textareaValue.value === '\n'){
        return null
      } else {
        msg_arr.value.push({
          key: msg_count++,
          avatar:'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg',
          rule:'user',
          message: textareaValue.value
        })
        sendMessage(textareaValue.value)
        msg_arr.value.push({
          key: msg_count++,
          avatar: avatar_ai,
          rule:'ai',
          message: " "
        })
        textareaValue.value=null
      }
    }
    return {
      enterIcon,searchIcon,ChatboxEllipsesIcon,GlassesIcon,
      showAI:ref(false),
      textareaValue,sendingText,
      msg_arr,reading,
      ai_type,ais,hanleUpdateValue,
      summarizeClick
    }
  }
}
</script>

<style lang="scss" scoped>
$gi:81px;
.sc-header{
  height: $gi;
  .sc-grid{
    height: $gi;
  }
}
.nav-title{
  //background: yellow;
  width: 10rem;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 21px;
  font-weight: bold;
  letter-spacing: 5px;
  &:hover{
    color: #1296db;
  }
  &:active{
    text-shadow: 2px 2px #f2f2f2;
    color: darken(#1296db,1.2);
  }
}
.nav-title-activate{
  color: #1296db;
}
.log-title{
  width: 10rem;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 36px;
  font-weight: bold;
  letter-spacing: 3px;
  text-shadow:2px 3px 1px pink;
}

.sc-footer{
  background: #000;
  color: #f2f2f2;
  ul{
    li:first-child{
      font-weight: bold;
    }
  }
}

.float-btn{
  position: absolute;
  display: flex;
  bottom: 3.6rem;
  right: 3.6rem;
  z-index: 12;
}

//ai图标全局设置
.ai-icon{
  position: fixed;
  right: 0;
  bottom: 9rem;
  width: 3.2rem;
  height: 2.7rem;
  background: #2080f0;
  z-index: 21;
  border-bottom-left-radius: 1.3rem;
  border-top-left-radius: 1.3rem;
  transition:.12s 0s ease-in all;
  box-sizing: border-box;
  padding-left: 1rem;
  &:hover{
    width: 5.6rem;
    box-shadow: 2px 2px 2px 2px #f2f2f2;
    transition:.12s 0s ease-in all;
  }
}

.item {
  display: flex;
  align-items: flex-start;
  &-ai{
    border-radius: 15px;
    margin: 1rem 0;
  }
  &-user{
    justify-content: end;
  }
}

.avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  margin-right: 10px;
}

.ai-window{
  position: relative;
  z-index: 18;
  width: 10rem;
  background: yellow;
}

.ai-window-content-bubble{
  box-sizing: border-box;
  padding: .5rem;
  border:  1px solid #f2f2f2;
  border-radius: 15px;
  margin-bottom: .5rem;
  transition: .24s 0s ease-in all;
  &:hover{
    transition: .24s 0s ease-in all;
    box-shadow: 2px 2px 2px 2px #f2f2f2;
  }
}

.user-window-content-bubble{
  box-sizing: border-box;
  padding: .5rem;
  border:  1px solid #f2f2f2;
  border-radius: 15px;
  margin-bottom: .5rem;
  transition: .24s 0s ease-in all;
  &:hover{
    transition: .24s 0s ease-in all;
    box-shadow: 2px 2px 2px 2px #f2f2f2;
  }
}

.icon-hover:hover{
  //背景颜色高亮
  background-color: #f2f2f2;
  //边框颜色高亮
  border-color: #f2f2f2;
  //阴影效果
  box-shadow: 2px 2px 2px 2px #f2f2f2;
  transition: .24s 0s ease-in all;
}
</style>
